﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Runtime.InteropServices;
using Bauglir.Ex;
using System.Net;
using System.Diagnostics;

namespace music_control
{
    public class Startup
    {
        [STAThread]
        static void Main()
        {

            try
            {

                // Get Reference to the current Process
                Process thisProc = Process.GetCurrentProcess();
                if (IsProcessOpen("music-control") == false)
                {
                    Start();
                }
                else
                {
                    // Check how many total processes have the same name as the current one
                    if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
                    {
                        // If ther is more than one, than it is already running.
                        System.Windows.MessageBox.Show("Application is already running. Look in the system tray.");

                        System.Environment.Exit(0);
                    }
                    else
                    {
                        Start();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops.. Please send a screenshot to musiccontrol@nbickel.com\n\n" + ex.ToString(), "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public static void Start()
        {
            App app = new App();
            app.InitializeComponent();

            app.InitTrayIcon();

            Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

            app.Run();

        }

        public static bool IsProcessOpen(string name)
        {
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains(name))
                {
                    return true;
                }
            }
            return false;
        }
    }
}


